package com.wo.cloud.code.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.wo.cloud.code.dto.CodeConfig;
import com.wo.cloud.code.entity.SysDataSource;
import com.wo.cloud.code.service.ISysDataSourceService;
import com.wo.cloud.code.util.FileUtil;
import com.wo.cloud.code.util.GeneratorUtil;
import com.wo.cloud.code.util.ZipUtil;
import com.wo.cloud.core.constant.SysConstant;
import com.wo.cloud.core.entity.Response;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/6/17 16:36
 * Description:
 */

@RequestMapping(SysConstant.SYS_CODE_BASE_URL)
@RestController
public class SysCodeController {
    public static final Logger log = LoggerFactory.getLogger(SysCodeController.class);

    @Autowired
    private ISysDataSourceService sysDataSourceService;

    /**
     * 获取数据库下所有表信息
     *
     * @param dataSourceId 数据源 id
     * @return
     */
    @GetMapping("/table-list")
    @ApiOperation(value = "获取库下所有表数据", notes = "获取库下所有表数据")
    public Response getTables(@RequestParam(required = true) String dataSourceId) {
        SysDataSource sysDataSource = sysDataSourceService.getById(dataSourceId);

        GlobalConfig globalConfig = new GlobalConfig();

        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.getDbType(sysDataSource.getDbType()));
        dataSourceConfig.setDriverName(sysDataSource.getDriverClass());
        dataSourceConfig.setPassword(sysDataSource.getPassword());
        dataSourceConfig.setUsername(sysDataSource.getUsername());
        dataSourceConfig.setUrl(sysDataSource.getUrl());

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();

        // 包配置
        PackageConfig pc = new PackageConfig();

        ConfigBuilder config = new ConfigBuilder(pc, dataSourceConfig, strategy, templateConfig, globalConfig);

//        AutoGenerator mpg = new AutoGenerator();
//        mpg.execute(); // 方法实现中 通过ConfigBuilder连接数据库

        // 获取所有表信息
        List<TableInfo> tableInfoList = config.getTableInfoList();
        return Response.data(tableInfoList);
    }

    @ApiOperation(value = "代码生成", notes = "代码生成")
    @PostMapping("/generator-code")
    public void execute(@RequestParam String packageName, @RequestParam(required = false) String prefix,
                        @RequestParam String modelName, @RequestParam String datasourceId,
                        @RequestParam(required = false) String tableName, String projectName,
                        HttpServletResponse response, HttpServletRequest request) {
        SysDataSource sysDataSource = sysDataSourceService.getById(datasourceId);
        String outputDir = System.getProperty("user.dir") + File.separator + "temp" + File.separator + "generator" + File.separator + projectName;
        CodeConfig config = new CodeConfig();
        config.setDbType(DbType.getDbType(sysDataSource.getName()));
        config.setUrl(sysDataSource.getUrl());
        config.setUsername(sysDataSource.getUsername());
        config.setPassword(sysDataSource.getPassword());
        config.setDriverName(sysDataSource.getDriverClass());
        config.setModelName(modelName);
        config.setOutputDir(outputDir);
        config.setPackageName(packageName);
        if (StrUtil.isNotBlank(tableName)) {
            config.setTableName(tableName);
        }
        if (StrUtil.isNotBlank(prefix)) {
            config.setPrefix(prefix);
        }
        config.setOutputDir(outputDir);

        GeneratorUtil.execute(config);
        String fileName = "code" + UUID.randomUUID().toString() + ".zip";
        String filePath = outputDir + File.separator + fileName;
        // 压缩目录
        String[] srcDir = {outputDir + File.separator + (config.getPackageName().substring(0, config.getPackageName().indexOf(".")))};
        try {
            ZipUtil.toZip(srcDir, filePath, true);
            FileUtil.download(filePath, fileName, true, response);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
